import cv2
import numpy as np
import pyautogui


def find_image_on_screen(img_path):
    # 截取当前屏幕
    screenshot = pyautogui.screenshot()
    screenshot = cv2.cvtColor(np.array(screenshot), cv2.COLOR_RGB2BGR)

    # 读取小图片
    template = cv2.imread(img_path, cv2.IMREAD_COLOR)
    size = template.width, template.height = template.shape[::-1]
    template_gray = cv2.cvtColor(template, cv2.COLOR_BGR2GRAY)
    w, h = template_gray.shape[::-1]

    # 将屏幕截图转换为灰度图
    screenshot_gray = cv2.cvtColor(screenshot, cv2.COLOR_BGR2GRAY)

    # 使用模板匹配在屏幕截图中查找小图片
    res = cv2.matchTemplate(screenshot_gray, template_gray, cv2.TM_CCOEFF_NORMED)
    threshold = 0.8  # 设置一个阈值，可以根据需要调整
    loc = np.where(res >= threshold)

    # 如果找到匹配区域，返回左上角坐标
    if len(loc[0]) > 0:
        pt = (loc[1][0], loc[0][0])
        print(size[0], size[1])
        return pt
    else:
        return None


# 示例用法
template_path = 'image/img.png'
coordinates = find_image_on_screen(template_path)
if coordinates:
    print(f"Found image at: {coordinates}")
    x = coordinates[0]
    y = coordinates[1]
    pyautogui.moveTo(x, y)
    pyautogui.click()
else:
    print("Image not found on screen.")
